<template>
  <div class="corpus-upload">
    <h3>上传语料库</h3>
    <el-upload
      class="upload-demo"
      action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileChange"
      accept=".txt"
    >
      <el-button type="primary" :loading="uploading">选择中-越语料文件</el-button>
      <template #tip>
        <div class="el-upload__tip">
          格式：每行 "中文句子[Tab]越南语句子"，如：想给爸爸打电话吗?	Cháu muốn gọi cho bố hả?
        </div>
      </template>
    </el-upload>
    
    <div v-if="selectedFileName" class="selected-file-info">
      已选择文件: {{ selectedFileName }}
    </div>
    
    <el-button 
      v-if="selectedFile" 
      type="success" 
      @click="handleUpload"
      :loading="uploading"
      style="margin-top: 10px;"
    >
      上传文件
    </el-button>
    
    <el-alert 
      v-if="result" 
      :title="result.message" 
      type="success" 
      show-icon 
      style="margin-top: 15px;"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 状态管理
const selectedFile = ref(null)
const selectedFileName = ref('')
const result = ref(null)
const uploading = ref(false)

// 生命周期钩子
onMounted(() => {
  // 配置axios基础URL
  axios.defaults.baseURL = 'http://127.0.0.1:5000'
})

// 处理文件选择
const handleFileChange = (file) => {
  selectedFile.value = file.raw
  selectedFileName.value = file.name
}

// 处理文件上传
const handleUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.error('请先选择文件')
    return
  }

  // 准备表单数据
  const formData = new FormData()
  formData.append('file', selectedFile.value)
  formData.append('uploaded_by', '1') // 临时固定用户ID

  try {
    uploading.value = true
    
    const response = await axios.post('/api/upload-corpus', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    result.value = response.data
    ElMessage.success(`成功导入 ${response.data.count} 条数据`)
    
    // 重置表单
    selectedFile.value = null
    selectedFileName.value = ''
    
  } catch (error) {
    console.error('上传失败:', error)
    const msg = error.response?.data?.error || '上传失败，请稍后重试'
    ElMessage.error(msg)
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.corpus-upload {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  text-align: left;
}

.selected-file-info {
  margin: 10px 0;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}
</style>

